package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.tanhua.dubbo.api.PeachblossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Peachblossom;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PeachblossomVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@SuppressWarnings("All")//去除所有黄色高亮
@Service
public class PeachblossomService {
    @DubboReference
    private VoiceApi voiceApi;

    @DubboReference
    private PeachblossomApi peachblossomApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer server;

    @DubboReference
    private UserInfoApi userInfoApi;

    //发送桃花传音
    public void save(MultipartFile soundFile) throws IOException {
        //上传文件
        InputStream inputStream = soundFile.getInputStream();//文件流
        long size = soundFile.getSize();//文件大小
        String originalFilename = soundFile.getOriginalFilename();//获取文件名
        int indexOf = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(indexOf + 1);//截取后缀名
        StorePath storePath = client.uploadFile(inputStream, size, substring, null);//上传视频
        String soundFileeUrl = server.getWebServerUrl() + storePath.getFullPath();//视频文件地址
        //构建对象
        Voice voice = new Voice();
        voice.setUserId(UserHolder.getUserId());
        voice.setSoundUrl(soundFileeUrl);
        voice.setCreated(System.currentTimeMillis());
        voiceApi.save(voice);
    }

    //桃花传音-接收语音
    public PeachblossomVo find() {
        Long id = UserHolder.getUserId();
        //查询Peachblossom数据
        Voice voice = voiceApi.find(id);
        if (voice == null) {
            throw new BusinessException(ErrorResult.voiceError());
        }
        UserInfo userInfo = userInfoApi.findUser(voice.getUserId());
        Peachblossom peachblossom =  peachblossomApi.findByUserId(id);
        peachblossom.setSoundUrl(voice.getSoundUrl());
        //判断次数
        if (peachblossom.getRemainingTimes() <= 0) {
            throw new BusinessException(ErrorResult.countError());
        }
        //返回
        int i = peachblossomApi.updateRemainingTimes(id);
        PeachblossomVo vo = PeachblossomVo.init(userInfo, peachblossom);
        vo.setRemainingTimes(i);
        return vo;
    }

}
